package com.xs.ahoi.hcxs;

import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Handler;
import android.support.v4.media.session.MediaSessionCompat;

import com.google.common.collect.Lists;
import com.xs.ahoi.hcxs.dao.DBHelper;
import com.xs.ahoi.hcxs.handler.BaseNotifyHandler;
import com.xs.ahoi.hcxs.handler.CrashHandler;
import com.xs.ahoi.hcxs.listener.HeadSetButtonListener;
import com.xs.ahoi.hcxs.receiver.NotificationPlayReceiver;
import com.xs.ahoi.hcxs.service.AudioFocusManager;
import com.xs.ahoi.hcxs.service.BGMService;
import com.xs.ahoi.hcxs.service.BGMServiceConnection;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.utils.LogUtil;
import com.xs.ahoi.hcxs.utils.ToastUtil;
import com.xs.ahoi.hcxs.utils.tts.TtsUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import okhttp3.OkHttpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * author: ahoi
 * date: 2018/6/22 11:50
 * description:
 */
public class Ahoi extends Application {

    private BGMServiceConnection bgmConn;
    private MediaSessionCompat session;
    private AudioFocusManager audioFocusManager;

    /**
     * 获取全局的application对象
     */
    private static Ahoi instance;

    // 用于存放所有启动的Activity的集合
    private List<Activity> activities;

    public static Ahoi getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    /**
     * 获取最后一个Activity
     */
    public Activity getActivity() {
        int size = activities.size();
        if (size > 0) {
            return activities.get(size - 1);
        }
        return null;
    }

    /**
     * 添加Activity
     */
    public void addOne(Activity activity) {
        if (!activities.contains(activity)) {
            activities.add(activity);
        }
    }

    /**
     * 销毁单个Activity
     */
    public void removeOne(Activity activity) {
        if (activities.contains(activity)) {
            activities.remove(activity);
            activity.finish();
        }
    }

    /**
     * 销毁所有的Activity
     */
    public void removeAll() {
        BookFactory.getInstance().stopPlay(true);
        BaseNotifyHandler.cancelAll();
        for (Activity activity : activities) {
            activity.finish();
        }
        activities = null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        activities = Lists.newArrayList();
        Ahoi.instance = this;

        // 初始化全局异常处理
        CrashHandler.getInstance().init(this);

        // 创建数据库查询工具类
        DBHelper.createInstance(this);

        // 创建阅读页面工具类
        BookFactory.getInstance();

        // 创建提示工具类
        ToastUtil.createInstance(this);

        // 创建TTS工具类
        TtsUtil.createTtsInstance(this);

        // 监听耳机断开，停止播放
        registerHeadsetPlugReceiver();

        // 注册通知栏按钮事件
        initNotificationPlayReceiver();

        // 初始化OkHttpUtils
        initOkHttpClient();

        // 初始化耳机按钮控制
        initMediaButton();

        // 焦点管理器
        audioFocusManager = new AudioFocusManager(this);

        // 启动背景音乐服务
        initBGM();
    }

    @Override
    public void onTerminate() {
        LogUtil.e("应用退出");
        super.onTerminate();
        if (bgmConn != null) {
            unbindService(bgmConn);
            bgmConn = null;
        }
    }

    // 初始化OkHttpUtils
    private void initOkHttpClient() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10L, TimeUnit.SECONDS) // 链接超时
                .readTimeout(10L, TimeUnit.SECONDS) // 读取超时
                .build(); // 其他配置

        OkHttpUtils.initClient(okHttpClient);
    }

    // 初始化监听耳机按键事件
    private void initMediaButton() {
        session = new MediaSessionCompat(this, "ahoi");
        session.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
        session.setActive(true);
        session.setCallback(new HeadSetButtonListener());
    }

    // 注册广播：耳机断开停止播放，插入开始播放
    private void registerHeadsetPlugReceiver() {
        registerReceiver(headsetPlugReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
        registerReceiver(headsetPlugReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
        registerReceiver(bluetoothReceiver, new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED));
    }

    // 监听耳机断开，停止播放
    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 有线耳机插入
            if (intent.hasExtra("state") && intent.getIntExtra("state", 0) == 1) {
                new Handler().postDelayed(() -> BookFactory.getInstance().startPlayIfNotPlay(), 2000);
            } else if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                BookFactory.getInstance().stopPlay(true);
            }
        }
    };

    // 监听蓝牙耳机插入，开始播放
    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 0);
            if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action) && bluetoothState == BluetoothAdapter.STATE_CONNECTED) {
                new Handler().postDelayed(() -> BookFactory.getInstance().startPlayIfNotPlay(), 2000);
            }
        }
    };

    // 注册广播
    private void initNotificationPlayReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(NotificationPlayReceiver.ACTION_PREV);
        intentFilter.addAction(NotificationPlayReceiver.ACTION_NEXT);
        intentFilter.addAction(NotificationPlayReceiver.ACTION_PAUSE);
        intentFilter.addAction(NotificationPlayReceiver.ACTION_PLAY);
        intentFilter.addAction(NotificationPlayReceiver.ACTION_CLOSE);
        registerReceiver(new NotificationPlayReceiver(), intentFilter);
    }

    // 启动背景音乐服务
    private void initBGM() {
        bgmConn = new BGMServiceConnection();
        Intent bgmIntent = new Intent(this, BGMService.class);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(bgmIntent);
//        } else {
        startService(bgmIntent);
//        }
        bindService(bgmIntent, bgmConn, BIND_AUTO_CREATE);
    }

    // 获取音乐播放控制器
    public BGMService.BGMBinder getBGMControl() {
        if (bgmConn != null) {
            return bgmConn.getPlayControl();
        }
        initBGM();
        if (bgmConn != null) {
            return bgmConn.getPlayControl();
        }
        LogUtil.e("BGMServiceConnection初始化失败");
        ToastUtil.show("BGMServiceConnection初始化失败");
        return null;
    }

    // 请求媒体焦点
    public static boolean getAuditFocus() {
        AudioFocusManager manager = getInstance().audioFocusManager;
        return manager != null && manager.requestAudioFocus();
    }

    // 释放媒体焦点
    public static void throwAuditFocus() {
        AudioFocusManager manager = getInstance().audioFocusManager;
        if (manager != null) {
            manager.throwAudioFocus();
        }
    }
}